package com.cocolover2.andbase.utils;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.cocolover2.andbase.utils.log.KLog;

/**
 * 文件下载管理器<br>
 * 1.使用系统的{@link DownloadManager}
 * 2.支持各种格式文件下载
 * 3.支持自定义下载文件名
 * 路径:/storage/emulated/0/Download/
 *
 * @since 1.1.1
 */
@Deprecated
public class DownLoadFileUtil {
    private Context context;
    private DownloadManager mDownloadManager;
    private DownloadReceiver receiver;
    private String mFileName;

    public DownLoadFileUtil(Context context) {
        this.context = context;
        receiver = new DownloadReceiver();
        mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }

    /**
     * 设置下载后的文件名
     *
     * @param fileName 文件名
     */

    public void setFileName(String fileName) {
        mFileName = fileName;
    }

    /**
     * 下载文件
     *
     * @param url 文件路径
     */
    public void download(String url) {
        DownloadManager.Request request = getDefaultRequest(url);
        if (request != null)
            mDownloadManager.enqueue(request);
    }


    private DownloadManager.Request getDefaultRequest(String url) {
        //创建下载请求
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //设置允许使用的网络类型，这里是移动网络和wifi都可以
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //显示下载通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //显示下载界面
        request.setVisibleInDownloadsUi(true);

        String[] suffixStr = url.split("\\.");
        if (suffixStr.length == 0) {
            KLog.e("下载的url路径不正确-->" + url);
            return null;
        }
        String fileName;

        if (!TextUtils.isEmpty(mFileName)) {
            fileName = mFileName;
        } else {
            String[] strings = url.split("/");
            if (strings.length > 0) {
                fileName = strings[strings.length - 1];
            } else {
                fileName = System.currentTimeMillis() + "." + suffixStr[suffixStr.length - 1];
            }
        }
        request.setTitle(fileName);
        //设置下载后文件存放的位置
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        return request;
    }

    private class DownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                // 查询
                Uri downloadUri = mDownloadManager.getUriForDownloadedFile(downloadId);
                if (downloadUri != null)
                    KLog.i("------->" + downloadUri.toString());
                else
                    KLog.i("------->找不到下载后的文件,可能文件不存在");
            }
        }
    }

    /**
     * 注册文件下载广播接收者
     */
    public void registerDownloadReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(receiver, filter);
    }

    /**
     * 解除注册文件下载广播接收者
     */
    public void unRegisterDownloadReceiver() {
        if (context != null && receiver != null)
            context.unregisterReceiver(receiver);
    }

}
